package com.zjcode.cdcer.service.impl;

import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjcode.cdcer.mapper.CerDetaildataImportOfficeInfoMapper;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.model.CerDetaildataImportInfo;
import com.zjcode.cdcer.model.CerDetaildataImportOfficeInfo;
import com.zjcode.cdcer.model.SysDict;
import com.zjcode.cdcer.service.CerDetaildataImportInfoService;
import com.zjcode.cdcer.service.CerDetaildataImportOfficeInfoService;
import com.zjcode.cdcer.service.SysDictService;
import com.zjcode.cdcer.service.SysUserService;
import com.zjcode.cdcer.utils.Utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class CerDetaildataImportOfficeInfoServiceImpl implements
                                                      CerDetaildataImportOfficeInfoService,
                                                      BaseService {

    @Autowired
    private CerDetaildataImportOfficeInfoMapper cerDetaildataImportOfficeInfoMapper;

    @Autowired
    private CerDetaildataImportInfoService cerDetaildataImportInfoService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public JsonObj batchInsert(PageData pageData) {

        Map<String, Object> data = new HashMap<>();
        data.put("count", 0);

        List<CerDetaildataImportInfo> list = cerDetaildataImportInfoService.getAllNoErrorData(
            pageData);
        if (!CollectionUtils.isEmpty(list)) {
            //插入正式库
            int count = cerDetaildataImportOfficeInfoMapper.batchInsert(list);
            //修改原数据状态
            cerDetaildataImportInfoService.updateCerDetaildataImportOfficeInfoStatus(pageData);
            data.put("count", count);
            return JsonObj.success(data);
        }
        return JsonObj.success(data);
    }

    @Override
    public Map<String, Object> getOfficePageData(PageData pageData) {
        String userId = (String) pageData.get("user");
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);

        // 读取区域信息
        pageData = Utils.transitionRegionInfo(pageData);

        MPage mPage = getPageInfo(pageData);

        //拿到字典数据集合
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> dictList = allCerDicts
            .stream()
            .collect(Collectors.groupingBy(SysDict::getDictType));

        //设置获取分页数据map
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> mapList = cerDetaildataImportOfficeInfoMapper.getOfficePageData(
            pageData);

        //设置返回数据map
        dictList
            .entrySet()
            .parallelStream()
            .forEach(entry -> {
                // key
                String key = entry.getKey();
                if (key.equals("xb_code")) {
                    key = "sex";
                }
                List<SysDict> dicts = entry.getValue();
                String finalKey = key;
                mapList
                    .stream()
                    .forEach(map -> {
                        Object o = map.get(finalKey);
                        if (o != null) {
                            Optional<SysDict> first = dicts
                                .stream()
                                .filter(sysDict -> sysDict
                                    .getDictValue()
                                    .equals(o.toString()))
                                .findFirst();
                            first.ifPresent(sysDict -> {
                                map.put(finalKey, sysDict.getDictName());
                            });
                        }
                    });
            });

        // 身份证, 给身份证加上掩码
        mapList
            .parallelStream()
            .forEach(each -> {
                String sfz = (String) each.get("sfz");
                if (sfz != null) {
                    each.put("sfz", sfz.substring(0, 6) + "********" + sfz.substring(14));
                }
            });

        return PaginationBuilder.buildResult(mapList,
                                             page.getTotal(),
                                             mPage.getCurrentPage(),
                                             mPage.getPageSize());
    }

    @Override
    public List<LinkedHashMap<String, Object>> queryAllOfficeExportData(PageData pageData) {
        String userId = (String) pageData.get("user");
        String ids = (String) pageData.get("ids");

        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);

        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
            .stream()
            .collect(Collectors.groupingBy(SysDict::getDictType));

        // 获取ids
        List<String> idList = new ArrayList<>();
        if (!StringUtils.isEmpty(userId)) {
            idList.addAll(Arrays.asList(ids.split("\\|")));
            pageData.put("idList", idList);
        }

        List<LinkedHashMap<String, Object>> infoList = cerDetaildataImportOfficeInfoMapper.queryAllExportData(
            pageData);

        keyListMap
            .entrySet()
            .parallelStream()
            .forEach(entry -> {
                // key
                String key = entry.getKey();
                if (key.equals("xb_code")) {
                    key = "sex";
                }
                List<SysDict> dicts = entry.getValue();
                String finalKey = key;
                infoList
                    .stream()
                    .forEach(map -> {
                        Object o = map.get(finalKey);
                        if (o != null) {
                            Optional<SysDict> first = dicts
                                .stream()
                                .filter(sysDict -> sysDict
                                    .getDictValue()
                                    .equals(o.toString()))
                                .findFirst();
                            first.ifPresent(sysDict -> {
                                map.put(finalKey,
                                        Optional
                                            .ofNullable(sysDict.getDictName())
                                            .orElse(""));
                            });
                        }
                    });
            });
        return infoList;
    }

    @Override
    public CerDetaildataImportOfficeInfo findDataById(String id) {
        return cerDetaildataImportOfficeInfoMapper.findDataById(id);
    }

}
